<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目信息" prop="info">
        <el-input
          v-model="queryParams.info"
          placeholder="请输入项目信息"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目负责人" prop="owner">
        <el-input
          v-model="queryParams.owner"
          placeholder="请输入项目负责人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目类型" prop="typeId">
        <el-input
          v-model="queryParams.typeId"
          placeholder="请输入项目类型"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['project:project:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['project:project:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['project:project:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['project:project:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-printer"
          size="mini"
          @click="handlePrint"
        >打印</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-data-analysis"
          size="mini"
          @click="generateStatistics"
        >统计</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="projectList" @selection-change="handleSelectionChange" ref="fileTable">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="项目ID" align="center" prop="id" sortable @sort-change="handleSort" />
      <el-table-column label="项目名称" align="center" prop="name" />
      <el-table-column label="项目信息" align="center" prop="info" />
      <el-table-column label="项目负责人" align="center" prop="owner" />
      <el-table-column label="最大成员数" align="center" prop="maxNum" sortable @sort-change="handleSort" />
      <el-table-column label="最大持续时间" align="center" prop="maxTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.maxTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="项目类型" align="center" prop="typeId" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['project:project:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['project:project:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改项目对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="项目信息" prop="info">
          <el-input v-model="form.info" placeholder="请输入项目信息" />
        </el-form-item>
        <el-form-item label="项目负责人" prop="owner">
          <el-input v-model="form.owner" placeholder="请输入项目负责人" />
        </el-form-item>
        <el-form-item label="最大成员数" prop="maxNum">
          <el-input v-model="form.maxNum" placeholder="请输入最大成员数" />
        </el-form-item>
        <el-form-item label="最大持续时间" prop="maxTime">
          <el-date-picker clearable
                          v-model="form.maxTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择最大持续时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="项目类型" prop="typeId">
          <el-input v-model="form.typeId" placeholder="请输入项目类型" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 统计对话框 -->
    <el-dialog title="项目负责人统计" :visible.sync="statisticsDialog" width="600px">
      <div class="statistics-container">
        <div v-for="(count, owner) in ownerCounts" :key="owner" class="bar" :style="{ width: count * 20 + 'px', height: '20px' }">
          <span>{{ owner }}: {{ count }}</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProject, getProject, delProject, addProject, updateProject } from "@/api/project/project";

export default {
  name: "Project",
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      projectList: [],
      title: "",
      open: false,
      statisticsDialog: false,
      ownerCounts: {}, // 用于存储项目负责人统计
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        info: null,
        owner: null,
        typeId: null,
        sortField: 'id',
        sortOrder: 'asc'
      },
      form: {},
      rules: {
        name: [{ required: true, message: "项目名称不能为空", trigger: "blur" }],
        info: [{ required: true, message: "项目信息不能为空", trigger: "blur" }],
        owner: [{ required: true, message: "项目负责人不能为空", trigger: "blur" }],
        maxNum: [{ required: true, message: "最大成员数不能为空", trigger: "blur" }],
        typeId: [{ required: true, message: "项目类型不能为空", trigger: "blur" }]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询项目列表 */
    getList() {
      this.loading = true;
      listProject(this.queryParams).then(response => {
        this.projectList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        info: null,
        owner: null,
        maxNum: null,
        maxTime: null,
        typeId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加项目";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getProject(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改项目";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateProject(this.form).then(response => {
              this.$message.success("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProject(this.form).then(response => {
              this.$message.success("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除项目编号为"' + ids + '"的数据项？').then(() => {
        return delProject(ids);
      }).then(() => {
        this.getList();
        this.$message.success("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('project/project/export', {
        ...this.queryParams
      }, `project_${new Date().getTime()}.xlsx`);
    },
    /** 打印按钮操作 */
    handlePrint() {
      const printContent = this.$refs.fileTable.$el.cloneNode(true); // 克隆表格内容
      const printWindow = window.open('', '_blank'); // 打开新窗口
      printWindow.document.write('<html><head><title>打印文档</title>');
      printWindow.document.write('<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">'); // 引入样式
      printWindow.document.write('</head><body>');
      printWindow.document.write(printContent.outerHTML); // 写入表格内容
      printWindow.document.write('</body></html>');
      printWindow.document.close(); // 关闭文档
      printWindow.print(); // 调用打印
      printWindow.close(); // 关闭打印窗口
    },
    /** 排序处理 */
    handleSort({ prop, order }) {
      this.queryParams.sortField = prop; // 设置排序字段
      this.queryParams.sortOrder = order === 'ascending' ? 'asc' : 'desc'; // 设置排序顺序
      this.getList(); // 重新获取列表
    },
    /** 生成统计数据 */
    generateStatistics() {
      const ownerCounts = {};
      this.projectList.forEach(project => {
        ownerCounts[project.owner] = (ownerCounts[project.owner] || 0) + 1;
      });

      this.ownerCounts = ownerCounts; // 更新统计数据
      this.statisticsDialog = true; // 显示统计对话框
    }
  }
};
</script>

<style>
.statistics-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.bar {
  margin: 8px 0;
  background-color: #42b983;
  color: white;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  transition: width 0.3s;
}
</style>
